import { defineComponent, ref, reactive, inject, watch, computed } from 'vue'
import '../styles//base-form.scss' 

const flowType = [{ name: '进入', value: 0 }, { name: '完成', value: 1 }, { name: '创建成功', value: 2 }]
interface FlowData {
    nodeList: any []
}

enum FlowEnum {
    // 发起节点
    START_NODE = 'start-node',
    // 结束节点
    END_NODE = 'end-node',
    // 汇合节点
    CONVERGE_NODE = 'converge-node',
    // 抄送节点
    CARBON_COPY_NODE = 'carbon-copy-node',
}


const baseRules = (formValue: Record<string, any>) => ({
    ruleName: [
        { required: true, message: '请输入规则名称', trigger: 'blur' }
    ],
    nodeId: [
        { required: true, message: '请选择节点', trigger: ['blur, change'] },
        {
            required: false,
            trigger: ['change', 'blur'],
            validator: (...args: [any, any, any]) => {
              const [rules, value, callback] = args;
              if (value.toString()) {
                if (!formValue.value['buttonName'] && rules.required) {
                  callback(new Error('请选择触发条件'));
                } else {
                  callback();
                }
              } else {
                callback();
              }
            }
          }
    ]
})

export default defineComponent({
    props: {
        formType: {
            type: Number,
            default: 0
        }
    },
    expose: ['formValidate', 'formResetFields'],
    setup(props) {
        const formRef = ref<any>(null)
        const formValue = ref<Record<string, any>>({
            flowStatus: 0, // 是进入还是完成
            ruleName: '', // 名称
            nodeId: '', // id
            buttonName: '' // button Name
        });
        const formRules = reactive(baseRules(formValue)) //表单提交规则
        const flowNodeButtons = ref([])
        const sliceFlowType = ref<Record<string, any>>([]) 
        const flowData = inject('flowData') as FlowData

        const changeRules = (flowStatus: number) => {
            flowStatus === 0 ? formRules['nodeId'][1].required = false : formRules['nodeId'][1].required = true // 修改必填校验
        }

        const filterNodeForShape = (shapes = [FlowEnum.START_NODE, FlowEnum.CONVERGE_NODE], flowStatus = 0) => {
            changeRules(flowStatus)
            return flowData?.nodeList?.filter(node => !shapes.includes(node.shape)) || []
        }

        const flowNodes = ref(filterNodeForShape()) // 过滤出符合条件的node

        const changeFormForKeyValue = (key: string, value: any) => {
            formValue.value[key] = value

            // 处理相关节点
            if(key === 'nodeId') {
                flowNodeButtons.value = []
                const nodeItem = flowNodes.value.find(node => node.id === value) || {}
                flowNodeButtons.value = nodeItem?.buttonList?.filter((btn: any) => btn.isOpen) ?? []
                // 判断buttonName是否存在
                const existButtonName = flowNodeButtons.value.find((item: Record<string, any>)=> item.name == formValue.value.buttonName)
                if(!existButtonName) {
                    formValue.value.buttonName = ''
                    formRef.value.clearValidate()
                }
            }
            
            // 处理相关选择节点状态
            if(key === 'flowStatus') {
                flowNodes.value = value === 0 ?  
                filterNodeForShape([FlowEnum.START_NODE, FlowEnum.CONVERGE_NODE], value) 
                : 
                filterNodeForShape([FlowEnum.END_NODE, FlowEnum.CONVERGE_NODE, FlowEnum.CARBON_COPY_NODE], value)
            }
        }

        const formValidate = (fun: Function) => formRef.value.validate(fun)

        const formResetFields = ()=> formRef.value.resetFields()


        watch(()=> formValue.value, (n)=> {
            changeFormForKeyValue('flowStatus', n.flowStatus)
            changeFormForKeyValue('nodeId', n.nodeId)
            changeRules(n.flowStatus)
        }, {
            deep: true
        })

        watch(()=> props.formType, (n)=> {
            // 判断是流程还是纯表单（0是流程 1是纯）
            if(n === 0) {
                sliceFlowType.value = flowType.slice(0, 2)
                 formValue.value.flowStatus = 0
                 formRules.nodeId[0].required = true
            } else {
                sliceFlowType.value = flowType.slice(2)
                formValue.value.flowStatus = 2
                formRules.nodeId[0].required = false
            }
        }, { immediate: true})

        return {
            formValidate,
            formResetFields,
            formValue,
            formRules,
            formRef,
            flowNodes,
            flowNodeButtons,
            sliceFlowType,
            changeFormForKeyValue
        }
    },

    render() {
        const { flowNodes, flowNodeButtons, formValue, formRules, sliceFlowType, changeFormForKeyValue, formType } = this

        return (
            <el-form label-position="top" 
                class="base-create-msg__form" 
                
                ref='formRef'  
                model={this.formValue}  
                rules={this.formRules}
                props={{
                    'hide-required-asterisk': true,
                    model: formValue,
                    rules: formRules
                }}
                hide-required-asterisk
               >
                <el-form-item label='规则名称' prop="ruleName"> 
                    <el-input class="form-name" value={formValue?.ruleName} placeholder="请输入规则名称" maxlength={20} onInput={(val: Event) => changeFormForKeyValue('ruleName', val)}></el-input>
                </el-form-item> 
                <el-form-item label='发送节点' prop="nodeId">
                    <div class="form-send-node">
                        { formType === 0 ? <span class="txt">当流程</span> : <span class="txt">当表单</span> }
                        <el-select class="select" value={formValue.flowStatus}  placeholder="请选择" onChange={(val: string)=> {
                             changeFormForKeyValue('flowStatus', val) 
                             this.formValue.nodeId = ''
                        }}>
                            {sliceFlowType.map((item: Record<string, any>)=> {
                                return (
                                    <el-option
                                        key={item.value}
                                        label={item.name}
                                        value={item.value}/>
                                    )
                            })}
                        </el-select>
                        {
                            formType === 0 ? (
                                <div>
                                    <el-select 
                                        class="select-flow-node" 
                                        value={formValue.nodeId}  
                                        placeholder="请选择" 
                                        onChange={(val: string)=> {
                                            this.formValue.nodeId = val
                                            this.formValue.buttonName = ''
                                        }}>
                                        {flowNodes.map(item=> {
                                            return (
                                                <el-option
                                                    key={item.id}
                                                    label={item.name}
                                                    value={item.id}/>
                                                )
                                        })}
                                    </el-select>
                                    { 
                                        formValue.flowStatus === 1 && <el-select class="select" value={formValue.buttonName}  placeholder="请选择" onChange={(val: string)=> changeFormForKeyValue('buttonName', val)}>
                                        {flowNodeButtons.map((item: any) => {
                                            return (
                                                <el-option
                                                    key={item.name}
                                                    label={item.buttonConfig.buttonName}
                                                    value={item.name}/>
                                                )
                                        })}
                                    </el-select>
                                    }
                                </div>
                            ) : null
                        }
                        <span class="txt ml_8">时发送</span>
                    </div>
                </el-form-item>
            </el-form>
        )
    }
})